//
//  XLNewMainViewController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2017/11/28.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLNewMainViewController.h"
#import "ConversationListViewController.h"
#import "XLHTTPSessionManager+Camgirl.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <ReactiveCocoa.h>
#import "XLMineViewController.h"
#import "XLCamgirlModel.h"
#import <BMHVideoConfig.h>
#import <BMHVideoPlayerControl.h>
#import <BMHVideoPlayerView.h>
#import "XLNewTopUpView.h"
#import "CallMakeViewController.h"
#import "HomeCallModel.h"
#import "WeixinHelper.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "XLNavgationViewController.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import "XLTopUpModel.h"
#import "XLOldMainTapViewController.h"
#import <StoreKit/StoreKit.h>
#import "BMHStoreObserver.h"
#import <ImSDK/TIMFriendshipManager.h>
#import "IMAChatViewController.h"


@interface XLNewMainViewController ()<BMHVideoPlayerControlDelegate,XLNewTopUpDelegate>
@property (nonatomic, strong) UIButton           *messageBtn;
@property (nonatomic, strong) UIButton           *mineBtn;
@property (nonatomic, strong) UILabel            *nick;
@property (nonatomic, strong) UILabel            *addrss;
@property (nonatomic, strong) UILabel            *callTimes;
@property (nonatomic, strong) UIImageView        *addressView;
@property (nonatomic, strong) UIImageView        *timesView;
@property (nonatomic, strong) UIImageView        *popView;
@property (nonatomic, strong) UILabel            *popTitle;
@property (nonatomic, strong) UIImageView        *callView;
@property (nonatomic, strong) UILabel            *callTitle;
@property (nonatomic, strong) UIImageView        *hostImgview;
@property (nonatomic, strong) BMHVideoPlayerView *playerView;
@property (nonatomic, strong) XLUserInfoModel    *userInfoModel;
@property (nonatomic, strong) XLCamgirlModel     *hostInforModel;
@property (nonatomic, strong) XLNewTopUpView     *topUpview;
@property (nonatomic, copy  ) NSString           *myMoney;
@property (nonatomic, copy  ) NSString           *actionType;
@property (nonatomic, strong) NSDictionary       *zfbDic;
@property (nonatomic, copy  ) NSString           *payorder;//支付宝订单号
@property (nonatomic, strong) UIButton           *videoCall;
@property (nonatomic, strong) NSMutableArray     *topUpMoneyArr;
@property (nonatomic, strong) NSMutableArray     *topUpJDArr;
@property (nonatomic, strong) UIView             *bgView;
@property (nonatomic, strong) UIView             *bottomView;
@property (nonatomic, strong) UIView             *redPoint;
@property (nonatomic, strong) UIView             *bottomupView;
@property (nonatomic, strong) NSString           *productIds;



@property (nonatomic, assign) BOOL makeSuccess;

@property (nonatomic, assign) BOOL shouldRefresh;
@end

@implementation XLNewMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = kWhiteColor;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.zfbDic   = [NSDictionary   dictionary];
    self.topUpMoneyArr = [NSMutableArray array];
    self.topUpJDArr    = [NSMutableArray array];
    
    [self MakeUI];
    [self playViewInit];
    [self addObserver];
    [self makeData];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
     return UIStatusBarStyleDefault;
}

- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"zhifusuccess" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self analyticsEvent8];
        [self refreshUserInfo];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self performSelector:@selector(refresh) withObject:nil afterDelay:60];
        UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] subscribeNext:^(id x) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refresh) object:nil];
        if (self.shouldRefresh) {
            [self makeData];
            self.shouldRefresh = NO;
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.makeSuccess) {
        XLOldMainTapViewController *mainVC = [[XLOldMainTapViewController alloc] init];
        XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
        [UIApplication sharedApplication].keyWindow.rootViewController = rootVC;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self analyticsEvent1];
    [self.playerView play];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refresh) object:nil];
    if (self.shouldRefresh) {
        [self makeData];
        self.shouldRefresh = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.playerView pause];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self performSelector:@selector(refresh) withObject:nil afterDelay:60];
}

- (void)refresh {
    if (self.navigationController.topViewController == self) {
        self.shouldRefresh = YES;
    }
}

-(void)playViewInit
{
    
    BMHVideoConfig *config = [[BMHVideoConfig alloc] init];
    self.playerView = [[BMHVideoPlayerView alloc] initWithFrame:self.view.frame delegate:self config:config];
    self.playerView.hidePlayControl = YES;
    self.playerView.coverView.contentMode = UIViewContentModeScaleAspectFill;
    self.playerView.coverView.image = [UIImage imageNamed:@""];
    [self.playerView.tx_player setRenderMode:RENDER_MODE_FILL_SCREEN];
    [self.view addSubview:self.playerView];
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self bringUpView:self.view];
}

- (void)removePlayerView {
    [self.playerView shutDownPlayer];
    [self.playerView removeFromSuperview];
}
#pragma mark - BMHVideoPlayerControlDelegate
- (void)videoPlaybackDidFinish {
    [self removePlayerView];
}

-(void)xlNewMessages
{
    _messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, XQScreenH-25-18,41, 25)];
    [_messageBtn setTitle:@"消息" forState:UIControlStateNormal];
    [_messageBtn setTitleColor:RGBA_HEX(0xffffff,0.7) forState:UIControlStateNormal];
    _messageBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [_messageBtn addTarget:self action:@selector(messageAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_messageBtn];
    
    _redPoint = [[UIView alloc] init];
    _redPoint.hidden = YES;
    _redPoint.layer.cornerRadius = 4;
    _redPoint.backgroundColor = RGB_HEX(0xff4a45);
    [_messageBtn addSubview:_redPoint];
    [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(8, 8));
        make.center.equalTo(_messageBtn).centerOffset(CGPointMake(18, -9));
    }];
    
}

-(void)MakeUI
{
    
    self.hostImgview = [[UIImageView alloc] initWithFrame:self.view.frame];
    self.hostImgview.clipsToBounds = YES;
    self.hostImgview.contentMode = UIViewContentModeScaleAspectFill;
    self.hostImgview.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.hostImgview setContentScaleFactor:[[UIScreen mainScreen] scale]];
    [self.view addSubview:self.hostImgview];
    //topUI
    //Info蒙版
    _bottomupView = [[UIView alloc] initWithFrame:CGRectMake(0,XQScreenH-200,XQScreenW,200)];
    [self.view addSubview:_bottomupView];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    
    gradient.frame = _bottomupView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)RGBA_HEX(0x000000, 0).CGColor,
                       (id)RGBA_HEX(0x000000, 0.4).CGColor,
                       nil];
    gradient.startPoint = CGPointMake(1, 0);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.locations = @[@0.2];
    [_bottomupView.layer addSublayer:gradient];
    
    UIView *  bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,XQScreenH-200, XQScreenW,148)];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    self.nick = [[UILabel alloc] initWithFrame:CGRectMake(15,47,XQScreenW-30,42)];
    self.nick.text = self.hostInforModel.NickName;
    self.nick.textColor = kWhiteColor;
    self.nick.font = [UIFont boldSystemFontOfSize:30];
    self.nick.layer.masksToBounds = YES;
    self.nick.layer.cornerRadius = 10;
    [self.bottomView addSubview:self.nick];
    
    
    
    self.addrss = [[UILabel alloc] initWithFrame:CGRectMake(15,93,100,24)];
    self.addrss.backgroundColor = RGBA_HEX(0x000000, 0.3);
    self.addrss.text = self.hostInforModel.HostCity;
    self.addrss.textColor = kWhiteColor;
    self.addrss.font = [UIFont systemFontOfSize:12.0];
    self.addrss.layer.masksToBounds =YES;
    self.addrss.layer.cornerRadius = 12;
    self.addrss.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:self.addrss];
    
    self.callTimes = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.addrss.frame)+9,CGRectGetMinY(self.addrss.frame), 120, 24)];
    self.callTimes.backgroundColor = RGBA_HEX(0x000000, 0.3);
    self.callTimes.text = [NSString stringWithFormat:@"已接听%@分钟",self.hostInforModel.WhenLong];
    self.callTimes.textColor = kWhiteColor;
    self.callTimes.font = [UIFont systemFontOfSize:12.0];
    self.callTimes.layer.masksToBounds = YES;
    self.callTimes.layer.cornerRadius = 12;
    self.callTimes.textAlignment = NSTextAlignmentCenter;
   [self.bottomView addSubview:self.callTimes];
    
    [self xlNewMessages];
    [self goMineBtn];
    [self videoChatView];
}

-(void)goMineBtn
{
    self.mineBtn = [[UIButton alloc] initWithFrame:CGRectMake(XQScreenW-25-41, XQScreenH-25-18, 41, 25)];
    [self.mineBtn setTitle:@"我的" forState:UIControlStateNormal];
    self.mineBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [self.mineBtn setTitleColor:RGBA_HEX(0xffffff,0.7) forState:UIControlStateNormal];
    [self.mineBtn addTarget:self action:@selector(mineBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mineBtn];
    
}

-(void)videoChatView
{
    
    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake((XQScreenW-160)/2, XQScreenH-42-14, 160, 42)];
    bgView.layer.masksToBounds = YES;
    bgView.layer.cornerRadius = 20;
    CAGradientLayer *gradient = [CAGradientLayer layer];
    
    gradient.frame = bgView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)RGB_HEX(0xff5f6d).CGColor,
                       (id)RGB_HEX(0xffc371).CGColor,
                       nil];
    gradient.startPoint = CGPointMake(0, 1);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.locations = @[@0.3];
    [bgView.layer addSublayer:gradient];
    [self.view addSubview:bgView];
    self.bgView = bgView;
    
    self.videoCall = [[UIButton alloc] initWithFrame:CGRectMake(0,0,160,42)];
    self.videoCall.layer.masksToBounds = YES;
    self.videoCall.layer.cornerRadius = 20;
    self.videoCall.titleLabel.font = [UIFont systemFontOfSize:16.0];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue] == NO) {
        [self.videoCall setTitle:@"和她视频" forState:UIControlStateNormal];
    } else {
        [self.videoCall setTitle:@"和她聊天" forState:UIControlStateNormal];
    }
    [self.videoCall setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [self.videoCall setImage:[UIImage imageNamed:@"xinliao_icon_shiping"] forState:UIControlStateNormal];
    self.videoCall.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,10);
    [self.videoCall addTarget:self action:@selector(videoChat:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:self.videoCall];
    
}

- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

-(void)videoChat:(UIButton *)sender
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue] == NO) {
        BMHLog(@"视频聊天");
        if ([[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] > 0) {
            [self analyticsEvent2];
            [self videoChatWithCamgirl:self.hostInforModel];
        } else {
            [self analyticsEvent5];
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
        }
    } else {
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[self.hostInforModel.userId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
    }
}

- (void)videoChatWithCamgirl:(XLCamgirlModel *)model {
    //model.userId = @"1227702";
    BMHLog(@"和%@去视频聊天", model.NickName);
    if ([model.userId isEqualToString:[[XLAccountManager shareInstance] model].Id]) {
        [MBProgressHUD showContent:@"不能自嗨哟！" toView:self.view];
        return;
    }
    NSString * useridStr = model.userId;
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    [MBProgressHUD showMessage:@"" toView:self.view];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        NSLog(@"=====dd个人资料json====%@",JSON);
        NSString  *status  =  JSON[@"result"][@"errcode"];
        [MBProgressHUD hideHUDForView:self.view];
        if ([F(@"%@", status) isEqualToString:@"803"]) {
            [MBProgressHUD showContent:@"对方取消了视频通话功能" toView:self.view];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:model.userId];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
                
            }];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                XLOldMainTapViewController *mainVC = [[XLOldMainTapViewController alloc] init];
                XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = rootVC;
            });
        }else{
            HomeCallModel *model = [[HomeCallModel alloc] initWithDict:JSON[@"result"][@"data"]];
            if ([self checkCameraAuthorization]) {
                [self chatWithModel:model];
            }
        }
    } failure:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

#pragma mark -
- (void)chatWithModel:(HomeCallModel *)model {
    NSString *uid = [[XLAccountManager shareInstance] model].Id;
    NSString *peeridStr = model.UserId;
    
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    NSString *free = @"0";
    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",locationString,@"Timestamp",natUser,@"Appsign", free, @"isFree",nil];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
        NSString * errcode  = JSON[@"result"][@"errcode"];
        NSString * videoID =  JSON[@"result"][@"data"][@"Id"];
        
        if ([errcode isEqualToString:@"0"])
        {
            NSString * callID =  [NSString stringWithFormat:@"%@",JSON[@"result"][@"data"][@"CallID"]];
            
            NSUser_save(videoID,kVideoID);//创建通话ID
            NSUser_save(callID,ChatToChatCallId);//创建通话ID
            
            //[HelpTool startTipViewWithText:@"通话发起成功!" duration:2.0f type:kTipViewTypeNone];
//            CallMakeViewController *make = [[CallMakeViewController alloc] init];
//            make.peerId = [NSString stringWithFormat:@"%@",model.UserId];
//            make.headStr = model.HeadImg;
//            make.nickNameStr = model.NickName;
//            make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
//            make.addressStr = model.HostCity;
//            make.ageStr = model.Age;
//            make.jobStr = model.job;
//            make.ismic = YES;
//            make.iscinema = YES;
//            make.callid = callID;
//            make.videoid = [NSString stringWithFormat:@"%@",videoID];
//            make.moneyStr = @"20";
//            make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
//            
//            self.makeSuccess = YES;
//            
//            [self presentViewController:make animated:YES completion:nil];
            
        }else if ([errcode isEqualToString:@"-2"])
        {
            //[HelpTool startTipViewWithText:@"你的账号余额不足，请充值！" duration:2.0f type:kTipViewTypeNone];
            [self analyticsEvent5];
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            
        }else if ([errcode isEqualToString:@"-10"])
        {
            [HelpTool startTipViewWithText:@"您的通话发起失败,请重新发起!" duration:2.0f type:kTipViewTypeNone];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                XLOldMainTapViewController *mainVC = [[XLOldMainTapViewController alloc] init];
                XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = rootVC;
            });
            
        }else if ([errcode isEqualToString:@"-3"])
        {
            [HelpTool startTipViewWithText:@"对方屏蔽了通话！" duration:2.0f type:kTipViewTypeNone];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                XLOldMainTapViewController *mainVC = [[XLOldMainTapViewController alloc] init];
                XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = rootVC;
            });
            
        }else if ([errcode isEqualToString:@"-4"])
        {
            [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                XLOldMainTapViewController *mainVC = [[XLOldMainTapViewController alloc] init];
                XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = rootVC;
            });
            
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"===创建通话====%@",JSON);
    } failure:^(NSError * _Nullable error) {
        NSLog(@"===创建通话失败===%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
}

-(void)makeData
{
    [MBProgressHUD showMessage:@"" toView:self.view];
    self.userInfoModel = [[XLAccountManager shareInstance] model];
    [[[XLHTTPSessionManager sharedXIUQUManager] getRandomCamgirlWithUserId:self.userInfoModel.Id] subscribeNext:^(id x) {
        NSLog(@"%@", x);
        [MBProgressHUD hideHUDForView:self.view];
        self.hostInforModel = x;
        [self analyticsEvent1];
        [self reloadUIData];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:@"加载失败" toView:self.view];
    }];
    
    [BMHHTTPSession GETBMHVideo:@"/api/v1/VideoChatInfo/GetRechareInfo" paraments:@{@"type":@"1"} success:^(id  _Nullable JSON) {
        
        NSLog(@"新用户列表:%@",JSON);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
            
        }else{
            
             [self getTopupList:JSON[@"data"]];
        }
       
        
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@", error);
        
        [MBProgressHUD showContent:@"加载失败" toView:self.view];
    }];
    
    @weakify(self);
    [RACObserve([IMAPlatformxl sharedInstance].conversationMgr, unReadMessageCount) subscribeNext:^(id x) {
        @strongify(self);
        self.redPoint.hidden = [x integerValue] <= 0;
    }];
    
}

-(void)getTopupList:(NSMutableArray *)arr
{
    for (int i = 0; i < arr.count; i++) {
        
        XLTopUpModel * topupMd = [XLTopUpModel modelWithDictionary:arr[i]];
        [self.topUpMoneyArr addObject:topupMd.money];
        [self.topUpJDArr    addObject:topupMd.jindou];
        if (i == 0) {
            self.myMoney = topupMd.money;
        }
    }
    
}

- (void)refreshUserInfo {
    [[[XLHTTPSessionManager sharedManager] getUserInfoWithUserId:[[XLAccountManager shareInstance] model].Id secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
        self.userInfoModel = x;
        [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
        [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
        [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
        self.userInfoModel.SecretKey = [[XLAccountManager shareInstance] model].SecretKey;
        [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
    } error:^(NSError *error) {
        
    }];
}

-(void)reloadUIData
{
    [self.hostImgview setImageWithURL:[NSURL URLWithString:self.hostInforModel.VideoImg] placeholder:[UIImage imageNamed:@""]];
    [self playOption];
    self.nick.text  = self.hostInforModel.NickName;
    CGSize addrssSize = [self sizeWithText:self.hostInforModel.HostCity font:[UIFont systemFontOfSize:12.0] maxSize:CGSizeMake(MAXFLOAT, 24)];
    if (addrssSize.width > 0) {
        self.addrss.frame = CGRectMake(15,93,addrssSize.width+20,24);
        self.addrss.text  = self.hostInforModel.HostCity;
        
    }else{
        
        self.addrss.frame = CGRectMake(0, 0, 0, 0);
        self.addrss.text  = @"";
    }
    
    CGSize callTimesSize = [self sizeWithText:[NSString stringWithFormat:@"已经通话%@分钟",self.hostInforModel.WhenLong] font:[UIFont systemFontOfSize:12.0] maxSize:CGSizeMake(MAXFLOAT, 24)];
    if (addrssSize.width >0 ) {
        self.callTimes.frame = CGRectMake(CGRectGetMaxX(self.addrss.frame)+9,CGRectGetMinY(self.addrss.frame), callTimesSize.width+20, 24);
        self.callTimes.text = [NSString stringWithFormat:@"已经通话%@分钟",self.hostInforModel.WhenLong];
    }else{
        
        self.callTimes.frame = CGRectMake(0, 0, 0, 0);
        self.callTimes.text  = @"";
    }
    
}

-(void)playOption
{
    if (self.playerView.superview == nil) {
        [self.view addSubview:self.playerView];
        [self.playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        [self bringUpView:self.view];
    }
    BMHVideoConfig *config = [[BMHVideoConfig alloc] init];
    [self.playerView.coverView setImageWithURL:[NSURL URLWithString:self.hostInforModel.VideoImg] placeholder:[UIImage imageNamed:@""]];
    [self.playerView reloadContentUrl:self.hostInforModel.VideoUrl config:config];
    [self.playerView.playControl removeFromSuperview];
    [self.playerView.tx_player setRenderMode:RENDER_MODE_FILL_SCREEN];
}

-(void)bringUpView:(UIView *)view
{
    [view bringSubviewToFront:self.bottomupView];
    [view bringSubviewToFront:self.nick];
    [view bringSubviewToFront:self.addressView];
    [view bringSubviewToFront:self.addrss];
    [view bringSubviewToFront:self.timesView];
    [view bringSubviewToFront:self.callTimes];
    [view bringSubviewToFront:self.messageBtn];
    [view bringSubviewToFront:self.callView];
    [view bringSubviewToFront:self.callTitle];
    [view bringSubviewToFront:self.popView];
    [view bringSubviewToFront:self.mineBtn];
    [view bringSubviewToFront:self.bgView];
    [view bringSubviewToFront:self.bottomView];
}

#pragma mark -XLNewTopUpDelegate
-(void)XLSelectedJD:(UIButton *)selectedBtn
{
    
    self.myMoney = [self.topUpMoneyArr objectAtIndex:selectedBtn.tag];
}


-(void)XLNewtestTopup
{
    self.myMoney = @"1";
}

//微信充值
-(void)XLNewWXZHIFU:(UIButton *)wxBtn;  //微信支付
{
    
    if (!([self.myMoney integerValue] > 0)) {
        
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
        
    } else {
        [self analyticsEvent7];
        [[WeixinHelper sharedWeixinHelper] getUrlWithWXMoney:self.myMoney Months:@"0" TranstypeId:@"1" RemarksInfo:RemarksRose KKOrder:@"" kkUserid:@""];
        
        self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
        
    }
    
}

//支付宝支付
-(void)XLNewZFBZHIFU:(UIButton *)zfbBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        [self analyticsEvent7];
        self.actionType = @"1";
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSString *uid = self.userInfoModel.Id;
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *actionType = self.actionType;
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        [[[XLHTTPSessionManager sharedManager] getZFBPlayOrder:self.userInfoModel.Id giftId:@"1" TransType:self.actionType payType:@"4" FeeType:@"" Money:self.myMoney PrivateInfo:zhf_PrivateKey Remarks:RemarksRose Months:@"0" secretKey:self.userInfoModel.SecretKey] subscribeNext:^(id x) {
            BMHLog(@"===支付宝创建订单===%@",x);
            NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
            self.payorder      = [NSString stringWithFormat:@"%@",x[@"data"]];
            if ([success isEqualToString:@"0"]) {
                NSString *money = [NSString stringWithFormat:@"%.2f", [self.myMoney floatValue]];
//                [ZhifuHelp InPutzhifubaoWithDingdan:self.payorder Money:money subjesct:RemarksRose body:RemarksRose successBlock:^{
//
//                    [self.navigationController popViewControllerAnimated:YES];
//                } failBlock:^{
//                    [self.navigationController popViewControllerAnimated:YES];
//                }];
                
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                
            } else {
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            
        } error:^(NSError *error) {
            NSLog(@"错误:%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showContent:@"加载失败,请重试!" toView:self.view];
            
        }];
    }
}

//AppstorePay(内购)
-(void)xlAppstorePay:(UIButton *)payBtn
{
    [self hadenlTopUpIn_purchase:payBtn];
}

#pragma mark AppStore内购支付订单
- (void)hadenlTopUpIn_purchase:(UIButton *)sender {
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        
        self.actionType = @"1";
        [MBProgressHUD showMessage:nil];
        NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *actionType = self.actionType;
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        self.zfbDic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"Type",uid,@"Userid",@"1",@"Giftid",self.actionType,@"Transtype",@"6",@"Paytype",@"",@"Feetype",self.myMoney,@"Money",zhf_PrivateKey,@"Privateinfo",RemarksRose,@"Remarks",@"0",@"Months",locationString,@"Timestamp",nat,@"Appsign",kAppTypeOrId,@"appid",KAPPFr,@"qudao",nil];
        
        [BMHHTTPSession GET:@"/MobileInterface/Pay/AliPay.ashx" paraments:self.zfbDic success:^(id  _Nullable JSON) {
            NSLog(@"===苹果内购创建订单===%@",JSON);
            NSString *errcode = JSON[@"result"][@"errcode"];
            self.payorder = JSON[@"result"][@"OrderNo"];
            if ([errcode isEqualToString:@"0"]) {
                self.productIds= [NSString stringWithFormat:@"XLVideoChat%@",self.myMoney];
                if([SKPaymentQueue canMakePayments])
                {
                    //buy AppStore Products
                    [[BMHStoreObserver sharedInstance] buy:self.productIds withPayMonyNum:self.myMoney andPayOrder:self.payorder];
                    self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                    
                }else
                {
                    BMHLog(@"不允许程序内付费");
                }
                
            } else {
                
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            [MBProgressHUD hideHUD];
        } failure:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
        }];
    }
}


- (void)topupViewDidDisAppear {
    [self analyticsEvent6];
}

-(void)mineBtnAction:(UIButton * )mineBtn
{
    //我的page
    [self analyticsEvent4];
    XLMineViewController * mineVC = [[XLMineViewController alloc] init];
    [self.navigationController pushViewController:mineVC animated:YES];
    
}

- (void)messageAction:(id)sender {
    //消息page
    [self analyticsEvent3];
    ConversationListViewController *vc = [[ConversationListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark - analyticsEvent
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"userid"];
    }
    if (self.hostInforModel.userId) {
        [attributes setObject:self.hostInforModel.userId ?: @"" forKey:@"camgirlid"];
    }
    return attributes.copy;
}

- (void)analyticsEvent1 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_newindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"xl_newindex" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent2 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_click_videochat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_click_videochat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent3 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_click_message" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_click_message" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent4 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_click_my" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_click_my" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent5 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_popup_charge" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_popup_charge" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent6 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_click_chargecancel" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_click_chargecancel" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent7 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_click_chargego" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_click_chargego" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent8 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"new_charge_back" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_newindex" action:@"new_charge_back" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

@end
